package com.rongzhe.house.order.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.exception.RongZheBusinessException;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.rest.BaseController;
import com.rongzhe.house.order.constants.ResponseCode;
import com.rongzhe.house.order.criteria.OrderCriteria;
import com.rongzhe.house.order.entity.CreateRequest;
import com.rongzhe.house.order.entity.GetSignRequest;
import com.rongzhe.house.order.enums.PayType;
import com.rongzhe.house.order.service.OrderService;
import com.rongzhe.house.pay.AliPayConfig;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by hggxg on 2017/11/19.
 */
@RestController
@RequestMapping("order")
public class OrderController extends BaseController {


    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ApiResult<String> list(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                  @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                  @RequestParam(value = "status", defaultValue = "1") Integer status) {

        ApiResult apiResult = new ApiResult();

        OrderCriteria orderCriteria = new OrderCriteria();
        orderCriteria.setUid(getCurrentUser().getUserId());
        orderCriteria.setCurrentPage(currentPage);
        orderCriteria.setPageSize(pageSize);
        orderCriteria.setStatus(status);

        apiResult.setData(orderService.list(orderCriteria));


        return apiResult;

    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ApiResult<String> detail(@RequestParam(value = "orderCode") String orderCode) {

        ApiResult apiResult = new ApiResult();

        OrderCriteria orderCriteria = new OrderCriteria();
        orderCriteria.setOrderCode(orderCode);

        apiResult.setData(orderService.detail(orderCriteria));

        return apiResult;
    }

    /**
     * 预览合同
     *
     * @param createRequest
     * @return
     */
    @PostMapping(value = "/showContract")
    public ApiResult showContract(@RequestBody CreateRequest createRequest) {
        Integer userId = getCurrentUser().getUserId();
        return orderService.showContract(createRequest.getItemId(), userId);
    }

    @ApiOperation(value = "创建", notes = "订单", httpMethod = "POST")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ApiImplicitParam(name = "createRequest", value = "商品和数量", required = true, dataType = "CreateRequest")
    public ApiResult<String> create(@RequestBody CreateRequest createRequest) throws RongZheBusinessException {

        ApiResult apiResult = new ApiResult();


        apiResult.setData(orderService.createOrder(createRequest.getItemId(), createRequest.getCount(), getCurrentUser().getUserId()));


        return apiResult;

    }

    @ApiOperation(value = "创建账单订单", notes = "账单订单", httpMethod = "POST")
    @RequestMapping(value = "/createBill", method = RequestMethod.POST)
    @ApiImplicitParam(name = "createRequest", value = "账单和数量", required = true, dataType = "CreateRequest")
    public ApiResult<String> createBill(@RequestBody CreateRequest createRequest) throws RongZheBusinessException {
        ApiResult apiResult = new ApiResult();
        apiResult.setData(orderService.createCustomOrder(createRequest.getBillId(), createRequest.getCount(), getCurrentUser().getUserId()));
        return apiResult;
    }

    @ApiOperation(value = "创建多账单订单", notes = "账单订单", httpMethod = "POST")
    @RequestMapping(value = "/createBills", method = RequestMethod.POST)
    @ApiImplicitParam(name = "createRequest", value = "账单列表", required = true, dataType = "CreateRequest")
    public ApiResult<String> createBills(@RequestBody List<CreateRequest> createRequests) throws RongZheBusinessException {
        ApiResult apiResult = new ApiResult();
        apiResult.setData(orderService.createBillsOrder(createRequests, getCurrentUser().getUserId()));
        return apiResult;
    }


    @ApiOperation(value = "获取第三方签名", notes = "订单", httpMethod = "POST")
    @RequestMapping(value = "/sign", method = RequestMethod.POST)
    @ApiImplicitParam(name = "signRequest", value = "订单号和支付类型", required = true, dataType = "GetSignRequest")
    public ApiResult<String> getSign(@RequestBody GetSignRequest signRequest) {

        ApiResult apiResult = new ApiResult();


        try {

            PayType payType = PayType.getPayTypeByValue(signRequest.getPayType());
            if (payType == null) {
                apiResult.setCode(Constants.UNKNOWN_PAY_TYPE);
                apiResult.setMessage("未知的支付类型");
                return apiResult;
            }

            apiResult.setData(orderService.getSign(signRequest.getCode(), payType));
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return apiResult;

    }

    @Autowired
    private AliPayConfig aliPayConfig;

    @RequestMapping(value = "/aliPayCallback", method = RequestMethod.POST)
    public String aliPayCallback(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("支付宝回调过来了");
        System.out.println(JSON.toJSONString(params));
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), aliPayConfig.getCharset(), "RSA2");
            System.out.println("校验签名成功");
            if (!flag) {
                return ResponseCode.getMessage(ResponseCode.ALI_PAY_CALLBACK_CHECK_FAIL);
            }
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
            //商户订单号
            String out_trade_no = params.get("out_trade_no");

            //支付宝交易号
            String trade_no = params.get("trade_no");

            //交易状态
            String trade_status = params.get("trade_status");
//            System.out.println("订单号" + out_trade_no);
//            System.out.println("支付宝交易号" + trade_no);
//            System.out.println("交易状态" + trade_status);
            if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                //业务处理
                orderService.paid(out_trade_no, trade_no, PayType.ALI.getType());
            }


        } catch (AlipayApiException e) {
            e.printStackTrace();

            return "fail";
        }

        return "success";
    }


    @RequestMapping(value = "/wxCallback")
    public String wxCallback(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {

        // 解析结果存储在HashMap
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();


        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }

//        JSONObject json = JSONObject.fromObject(map);

        System.out.println("===消息通知的结果：" + JSON.toJSONString(map) + "==========================");
        System.out.println("===return_code===" + map.get("return_code"));
        System.out.println("===return_msg===" + map.get("return_msg"));
        System.out.println("===out_trade_no===" + map.get("out_trade_no"));

        if (map.get("return_code").equals("SUCCESS")) {

            /**
             *支付成功之后的业务处理
             */

            // 释放资源
            inputStream.close();

            orderService.paid(map.get("out_trade_no"), map.get("transaction_id"), PayType.WX.getType());
            //bis.close();
            return "SUCCESS";
        }

        if (map.get("return_code").equals("FAIL")) {

            /**
             *支付失败后的业务处理
             */

            // 释放资源
            inputStream.close();

            return "FAIL";
        }

        // 释放资源
        inputStream.close();

        return "SUCCESS";

    }


    @ApiOperation(value = "结果查询", notes = "订单", httpMethod = "GET")
    @RequestMapping(value = "/result/query", method = RequestMethod.GET)
    @ApiImplicitParam(name = "signRequest", value = "订单号", required = true, dataType = "GetSignRequest")
    public ApiResult<String> queryResult(@RequestBody GetSignRequest signRequest) {

        ApiResult apiResult = new ApiResult();


        apiResult.setData(orderService.query(signRequest.getCode()));


        return apiResult;

    }

}
